package MyTest;

import java.io.*;
import java.net.Socket;
import java.util.ArrayList;
import java.util.HashMap;

public class MyRunnable implements Runnable{
    BufferedWriter bw;
    BufferedReader br;
    BufferedReader fbr = null;
    Socket socket;
    static ArrayList<Socket> list = new ArrayList<>();

    public MyRunnable(Socket socket)
    {
        this.socket = socket;
        list.add(socket);
    }
    @Override
    public void run() {
        try {
            //创建网络输入流
            br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            //创建网络输出流
            bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            //登录操作
            while (true) {
                //读取客户端送来的登录信息
                //创建文件输入流
                fbr = new BufferedReader(new FileReader("/Users/lujingxiang/IdeaProjects" +
                        "/ChatRoom/src/MyTest/userinfo.properties"));
                String line = br.readLine();
                String userNameInput = line.split("=")[0];
                String passwordInput = line.split("=")[1];
                //读取文件输入的信息,逐个比对
                HashMap<String,String> map = new HashMap<>();
                String rightInfo;
                while ((rightInfo=fbr.readLine())!=null)
                {
                    String userName = rightInfo.split("=")[0];
                    String password = rightInfo.split("=")[1];
                    map.put(userName,password);
                }
                //先验证用户名是否存在
                if(!map.containsKey(userNameInput))
                {
                    write("用户名不存在");
                    continue;
                }
                //密码是否正确
                if(!map.get(userNameInput).equals(passwordInput))
                {
                    write("密码错误");
                    continue;
                }
                write("登录成功");
                break;
            }
            //聊天开始

            while(true)
            {
                //读入客户端传过来的信息
                String line = br.readLine();
                //广播到所有客户端，遍历集合
                for (Socket s : list) {
                    BufferedWriter rbw = new BufferedWriter(
                            new OutputStreamWriter(s.getOutputStream()));
                    rbw.write(line);
                    rbw.newLine();
                    rbw.flush();
                }
                if("886".equals(line))
                {
                    break;
                }
            }

        } catch (IOException e) {
            System.out.println("代码出错");
            throw new RuntimeException(e);
        }
        finally {
            try {
                socket.close();
                fbr.close();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }
    public void write(String str) throws IOException {
        bw.write(str);
        bw.newLine();
        bw.flush();
    }
}
